package com.cskaoyan.shopping.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.shopping.dto.CartProductDto;
import com.cskaoyan.shopping.form.CartRequest;
import com.cskaoyan.shopping.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: bwj
 * @Date: 2022/09/20/19:37
 * @Description:
 */
@RestController
public class ShoppingCartController {
    @Autowired
    ShoppingCartService cartService;

    /**
     * @Author: 宾文杰 @Description: 获得购物车列表 @Date: 2022/9/20
     */
    @GetMapping("shopping/carts")
    public ResponseData<List<CartProductDto>> getCart(HttpServletRequest request) {
        //获取请求头中的uid
        String userInfo = request.getHeader("user_info");
        JSONObject object = JSON.parseObject(userInfo);
        Long uid = Long.parseLong(object.get("uid").toString());
        List<CartProductDto> cartDtos = cartService.carts(uid);
        return new ResponseUtil<List<CartProductDto>>().setData(cartDtos);
    }
    /**
     * @Author: 宾文杰 @Description: 更新商品购物车 @Date: 2022/9/20
     */
    @PutMapping("shopping/carts")
    public ResponseData NewCarts(@Valid @RequestBody CartRequest newCartsBo) {
        cartService.newCart(newCartsBo);
        return new ResponseUtil<String>().setData(null);
    }

    /**
     * @Author: 宾文杰 @Description: 删除购物车中的商品 @Date: 2022/9/20
     */
    @DeleteMapping("shopping/carts/{uid}/{pid}")
    public ResponseData deleteCart(@PathVariable Integer uid, @PathVariable Integer pid) {
        cartService.deleteCart(uid,pid);
        return new ResponseUtil<String>().setData(null);
    }

    /**
     * @Author: 宾文杰 @Description: 添加商品到购物车 @Date: 2022/9/20
     */
    @PostMapping("shopping/carts")
    public ResponseData putCart(@Valid @RequestBody CartRequest cartRequest) {
        cartService.putCart(cartRequest);
        return new ResponseUtil<String>().setData(null);
    }

    /**
     * @Author: 宾文杰 @Description: 删除购物车全部商品 @Date: 2022/9/20
     */
    @DeleteMapping("shopping/items/{uid}")
    public ResponseData deleteItems(@PathVariable Long uid) {
        cartService.deleteItems(uid);
        return new ResponseUtil<String>().setData(null);
    }

    /**
    * @Author: 宾文杰 @Description: 全选购物车中商品，修改对应状态 @Date: 2022/9/20
    */
    @PutMapping("shopping/items")
    public ResponseData newItems(@RequestBody CartRequest cartRequest) {
        cartService.newItems(cartRequest);
        return new ResponseUtil<String>().setData(null);
    }
}
